#include "metadata.h"

void read_image(char *mp3, unsigned char **image, int *image_size) {
    /* prepate av context */
    AVFormatContext *p_format_context = avformat_alloc_context();
    if (avformat_open_input(&p_format_context, mp3, NULL, NULL) != 0)
        return;

    /* iterate fields */
    for (int i = 0; i < p_format_context->nb_streams; i++) {
        /* if a picture is attached */
        if (p_format_context->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC) {
            AVPacket packet = p_format_context->streams[i]->attached_pic;
            /* signal back where to look for data and how long it is */
            *image = malloc(packet.size);
            /* memcpy because libavformat weirdly transforms packet.data */
            memcpy(*image, packet.data, packet.size);
            *image_size = packet.size;
            break;
        }
    }
    avformat_close_input(&p_format_context);
}